<template>
  <div class="advertisement-management">
    <div class="page-header">
      <h1>广告管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="openCreateDialog">
          <el-icon><Plus /></el-icon>
          新增广告
        </el-button>
      </div>
    </div>
    
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="广告标题">
          <el-input v-model="searchForm.title" placeholder="搜索广告标题" clearable />
        </el-form-item>
        <!--
        <el-form-item label="广告位置">
          <el-select v-model="searchForm.positionId" placeholder="选择广告位置" clearable>
            <el-option v-for="item in positionOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        -->
        <el-form-item label="广告状态">
          <el-select v-model="searchForm.status" placeholder="选择广告状态" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="advertisements"
        style="width: 100%"
        border
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="title" label="广告标题" min-width="150" show-overflow-tooltip />
        <el-table-column label="广告图片" width="120">
          <template #default="scope">
            <el-image
              :src="scope.row.imageUrl"
              :preview-src-list="[scope.row.imageUrl]"
              fit="cover"
              style="width: 80px; height: 45px; border-radius: 4px;"
            />
          </template>
        </el-table-column>
        <el-table-column label="广告位置" width="120">
          <template #default="scope">
            {{ getPositionName(scope.row.positionId) }}
          </template>
        </el-table-column>
        <el-table-column label="展示时间" min-width="200">
          <template #default="scope">
            {{ formatTimeRange(scope.row.startTime, scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="80" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="数据统计" width="150">
          <template #default="scope">
            <div>展示: {{ scope.row.viewCount || 0 }}</div>
            <div>点击: {{ scope.row.clickCount || 0 }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 0"
              size="small"
              type="success"
              @click="handlePublish(scope.row)"
            >
              发布
            </el-button>
            <el-button
              v-if="scope.row.status === 1"
              size="small"
              type="warning"
              @click="handleUnpublish(scope.row)"
            >
              下线
            </el-button>
            <el-button
              v-if="scope.row.status === 2"
              size="small"
              type="success"
              @click="handlePublish(scope.row)"
            >
              上线
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑广告对话框 -->
    <el-dialog
      :title="dialogType === 'create' ? '新增广告' : '编辑广告'"
      v-model="dialogVisible"
      width="650px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="adFormRef"
        :model="adForm"
        :rules="adRules"
        label-width="100px"
      >
        <el-form-item label="广告标题" prop="title">
          <el-input v-model="adForm.title" placeholder="请输入广告标题" />
        </el-form-item>
        
        <el-form-item label="广告描述" prop="description">
          <el-input
            v-model="adForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入广告描述"
          />
        </el-form-item>
        
        <el-form-item label="广告图片" prop="imageUrl">
          <el-upload
            class="ad-image-uploader"
            :action="uploadImageAction"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            name="files"
          >
            <img v-if="adForm.imageUrl" :src="adForm.imageUrl" class="ad-image" />
            <el-icon v-else class="ad-image-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="image-tip">建议尺寸: 1200 x 400 像素, 格式: JPG/PNG, 大小: 不超过2MB</div>
        </el-form-item>
        
        <el-form-item label="链接地址" prop="linkUrl">
          <el-input v-model="adForm.linkUrl" placeholder="请输入广告链接地址" />
        </el-form-item>
        
        <el-form-item label="广告位置" prop="positionId">
          <el-select v-model="adForm.positionId" placeholder="请选择广告位置">
            <el-option v-for="item in positionOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="展示时间段" prop="timeRange">
          <el-time-picker
            v-model="adForm.startTime"
            placeholder="开始时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            :disabled-hours="disabledStartHours"
            :picker-options="{
              selectableRange: '00:00:00 - 23:59:59'
            }"
          />
          <span style="margin: 0 10px;">至</span>
          <el-time-picker
            v-model="adForm.endTime"
            placeholder="结束时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            :disabled-hours="disabledEndHours"
            :picker-options="{
              selectableRange: '00:00:00 - 23:59:59'
            }"
          />
          <div class="form-tip">每天在此时间段内展示广告</div>
        </el-form-item>
        
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="adForm.priority" :min="0" :max="100" />
          <span class="form-tip">数字越大优先级越高</span>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdForm" :loading="submitting">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Upload } from '@element-plus/icons-vue';
import { 
  getAdvertisementList, 
  searchAdvertisements, 
  createAdvertisement, 
  updateAdvertisement, 
  deleteAdvertisement, 
  publishAdvertisement, 
  unpublishAdvertisement 
} from '@/api/advertisement';
import { formatDate as formatDateUtil } from '@/utils/format';

// 状态变量
const loading = ref(false);
const advertisements = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogVisible = ref(false);
const dialogType = ref('create'); // 'create' 或 'edit'
const submitting = ref(false);
const adFormRef = ref(null);

// 搜索表单
const searchForm = reactive({
  title: '',
  positionId: '',
  status: ''
});

// 广告表单
const adForm = reactive({
  adId: null,
  title: '',
  description: '',
  imageUrl: '',
  linkUrl: '',
  positionId: '',
  startTime: '',
  endTime: '',
  priority: 0,
  status: 0
});

// 表单验证规则
const adRules = {
  title: [
    { required: true, message: '请输入广告标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 255, message: '描述长度不能超过255个字符', trigger: 'blur' }
  ],
  imageUrl: [
    { required: true, message: '请上传广告图片', trigger: 'change' }
  ],
  positionId: [
    { required: true, message: '请选择广告位置', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
};

// 广告位置选项
const positionOptions = [
  { value: 1, label: '首页轮播图' },
  { value: 2, label: '首页推荐位' },
  { value: 3, label: '景点详情页' },
  { value: 4, label: '侧边栏广告' }
];

// 广告状态选项
const statusOptions = [
  { value: 0, label: '待发布' },
  { value: 1, label: '已发布' },
  { value: 2, label: '已下线' }
];

// 添加上传路径计算属性
const uploadImageAction = computed(() => {
  return `${import.meta.env.VITE_API_BASE_URL}/advertisement/upload/image`;
});

// 上传图片所需的请求头
const uploadHeaders = computed(() => {
  return {
    Authorization: `Bearer ${localStorage.getItem('token')}`
  };
});

// 获取广告列表
const fetchAdvertisements = async () => {
  loading.value = true;
  try {
    const response = await getAdvertisementList({
      pageNum: currentPage.value,
      pageSize: pageSize.value
    });
    
    if (response.code === 200) {
      advertisements.value = response.data.list || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取广告列表失败');
    }
  } catch (error) {
    console.error('获取广告列表失败:', error);
    ElMessage.error('获取广告列表失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 搜索广告
const handleSearch = async () => {
  currentPage.value = 1;
  loading.value = true;
  
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    };
    
    // 移除空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key];
      }
    });
    
    const response = await searchAdvertisements(params);
    
    if (response.code === 200) {
      advertisements.value = response.data.list || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '搜索广告失败');
    }
  } catch (error) {
    console.error('搜索广告失败:', error);
    ElMessage.error('搜索广告失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  handleSearch();
};

// 打开创建广告对话框
const openCreateDialog = () => {
  dialogType.value = 'create';
  resetAdForm();
  dialogVisible.value = true;
};

// 重置广告表单
const resetAdForm = () => {
  adForm.adId = null;
  adForm.title = '';
  adForm.description = '';
  adForm.imageUrl = '';
  adForm.linkUrl = '';
  adForm.positionId = '';
  adForm.startTime = '';
  adForm.endTime = '';
  adForm.priority = 0;
  adForm.status = 0;
  
  if (adFormRef.value) {
    adFormRef.value.resetFields();
  }
};

// 处理编辑广告
const handleEdit = (row) => {
  dialogType.value = 'edit';
  adForm.adId = row.adId;
  adForm.title = row.title;
  adForm.description = row.description || '';
  adForm.imageUrl = row.imageUrl;
  adForm.linkUrl = row.linkUrl || '';
  adForm.positionId = row.positionId;
  
  // 确保时间格式正确
  console.log('原始时间:', row.startTime, row.endTime);
  
  // 如果时间已经是HH:mm:ss格式，直接使用
  if (typeof row.startTime === 'string' && row.startTime.match(/^\d{2}:\d{2}:\d{2}$/)) {
    adForm.startTime = row.startTime;
  } else {
    // 否则尝试格式化
    try {
      adForm.startTime = formatDate(row.startTime, 'HH:mm:ss');
    } catch (e) {
      console.error('格式化开始时间失败:', e);
      adForm.startTime = '00:00:00'; // 默认值
    }
  }
  
  if (typeof row.endTime === 'string' && row.endTime.match(/^\d{2}:\d{2}:\d{2}$/)) {
    adForm.endTime = row.endTime;
  } else {
    try {
      adForm.endTime = formatDate(row.endTime, 'HH:mm:ss');
    } catch (e) {
      console.error('格式化结束时间失败:', e);
      adForm.endTime = '23:59:59'; // 默认值
    }
  }
  
  console.log('设置后的时间:', adForm.startTime, adForm.endTime);
  
  adForm.priority = row.priority || 0;
  adForm.status = row.status || 0;
  
  dialogVisible.value = true;
};

// 提交广告表单
const submitAdForm = async () => {
  if (!adFormRef.value) return;
  
  await adFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    submitting.value = true;
    
    try {
      const formData = {
        title: adForm.title,
        description: adForm.description,
        imageUrl: adForm.imageUrl,
        linkUrl: adForm.linkUrl,
        positionId: adForm.positionId,
        startTime: adForm.startTime,
        endTime: adForm.endTime,
        priority: adForm.priority,
        status: adForm.status
      };
      
      let response;
      
      if (dialogType.value === 'create') {
        response = await createAdvertisement(formData);
      } else {
        response = await updateAdvertisement(adForm.adId, formData);
      }
      
      if (response.code === 200) {
        ElMessage.success(dialogType.value === 'create' ? '创建广告成功' : '更新广告成功');
        dialogVisible.value = false;
        fetchAdvertisements();
      } else {
        ElMessage.error(response.message || (dialogType.value === 'create' ? '创建广告失败' : '更新广告失败'));
      }
    } catch (error) {
      console.error(dialogType.value === 'create' ? '创建广告失败:' : '更新广告失败:', error);
      ElMessage.error(dialogType.value === 'create' ? '创建广告失败，请稍后再试' : '更新广告失败，请稍后再试');
    } finally {
      submitting.value = false;
    }
  });
};

// 处理删除广告
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该广告吗？此操作不可恢复。',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteAdvertisement(row.adId);
      
      if (response.code === 200) {
        ElMessage.success('删除广告成功');
        fetchAdvertisements();
      } else {
        ElMessage.error(response.message || '删除广告失败');
      }
    } catch (error) {
      console.error('删除广告失败:', error);
      ElMessage.error('删除广告失败，请稍后再试');
    }
  }).catch(() => {});
};

// 处理发布广告
const handlePublish = async (row) => {
  try {
    const response = await publishAdvertisement(row.adId);
    
    if (response.code === 200) {
      ElMessage.success('发布广告成功');
      fetchAdvertisements();
    } else {
      ElMessage.error(response.message || '发布广告失败');
    }
  } catch (error) {
    console.error('发布广告失败:', error);
    ElMessage.error('发布广告失败，请稍后再试');
  }
};

// 处理下线广告
const handleUnpublish = async (row) => {
  try {
    const response = await unpublishAdvertisement(row.adId);
    
    if (response.code === 200) {
      ElMessage.success('下线广告成功');
      fetchAdvertisements();
    } else {
      ElMessage.error(response.message || '下线广告失败');
    }
  } catch (error) {
    console.error('下线广告失败:', error);
    ElMessage.error('下线广告失败，请稍后再试');
  }
};

// 处理图片上传成功
const handleImageSuccess = (response, uploadFile) => {
  if (response.code === 200 && response.data && response.data.length > 0) {
    // 后端返回的是图片URL数组，我们取第一个
    adForm.imageUrl = response.data[0];
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error(response.message || '上传图片失败');
  }
};

// 上传图片前的验证
const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;
  
  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
    return false;
  }
  
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
    return false;
  }
  
  return true;
};

// 获取广告位置名称
const getPositionName = (positionId) => {
  const position = positionOptions.find(item => item.value === positionId);
  return position ? position.label : '未知位置';
};

// 获取广告状态名称
const getStatusName = (status) => {
  const statusObj = statusOptions.find(item => item.value === status);
  return statusObj ? statusObj.label : '未知状态';
};

// 获取广告状态对应的标签类型
const getStatusType = (status) => {
  switch (status) {
    case 0:
      return 'info';
    case 1:
      return 'success';
    case 2:
      return 'danger';
    default:
      return 'info';
  }
};

// 格式化日期
const formatDate = (date, format) => {
  return formatDateUtil(date, format);
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchAdvertisements();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchAdvertisements();
};

// 禁用开始时间的小时选择
const disabledStartHours = () => {
  return [];
};

// 禁用结束时间的小时选择
const disabledEndHours = () => {
  return [];
};

// 在表格中显示时间段
const formatTimeRange = (startTime, endTime) => {
  // 直接返回时间字符串，不进行格式转换
  return `${startTime || '未设置'} - ${endTime || '未设置'}`;
};

// 页面加载时获取广告列表
onMounted(() => {
  fetchAdvertisements();
});
</script>

<style scoped>
.advertisement-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.ad-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 300px;
  height: 100px;
}

.ad-image-uploader:hover {
  border-color: #409EFF;
}

.ad-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.ad-image {
  width: 300px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.image-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}
</style> 